package com.lsc.record.config;

import java.util.List;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.datasource.FlexDataSource;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import com.zaxxer.hikari.HikariDataSource;

@Component
public class DataSourceInitListener implements ApplicationListener<ContextRefreshedEvent>{

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		FlexDataSource datasource = FlexGlobalConfig.getDefaultConfig().getDataSource();
		List<Row> extDbs = Db.selectAll("DM_DATASOURCE_CONFIG");
		if(extDbs!=null && extDbs.size()>0) {
			System.out.println("有额外的数据源");
			
			for (Row row : extDbs) {
				String name= row.getString("NAME");
				String driverClassName= row.getString("DB_DRIVER");
				String dbUrl= row.getString("DB_URL");
				String dbUser= row.getString("DB_USER");
				String dbPwd= row.getString("DB_PWD");
				
				HikariDataSource newDataSource = new HikariDataSource();
				newDataSource.setDriverClassName(driverClassName);
				newDataSource.setJdbcUrl(dbUrl);
				newDataSource.setUsername(dbUser);
				newDataSource.setPassword(dbPwd);
				
				datasource.addDataSource(name, newDataSource);
			}
		}else {
			System.out.println("没有额外的数据源");
		}
		System.out.println(datasource.getDataSourceMap().keySet());
		
	}

}
